import { Modal, Button, ConfigProvider, DatePicker, Space, Select, message } from 'antd';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import { useTablePipeline } from 'ali-react-table';
import React, { useEffect } from 'react';
import 'moment/locale/zh-cn';
import moment from 'moment';

import { TjTable, TjChart } from '@/pages/ETrade/components/index.js';
import { TRDefault, PageLoading } from '@/components/index.js';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';
import { useTRState } from '#/utils/trHooks.jsx';
import { HttpCode } from '#/utils/contacts.js';

import { queryProvincialSpotBiddingPlan } from '../../../service';
import { columns } from '../../../dictionary';

import styles from './index.less';

const { RangePicker } = DatePicker;
const ConfirmModalComponent = (props) => {
  const { onPress, power, formValue } = props;
  const [state, setState] = useTRState({
    visible: true,
    error: '',
    loading: true,
    marketId: power[0].marketId,
    stationId: power[0].stationId,
    calendarDate: [moment(), moment()],
    stationOptions: power[0].children,
    dataSource: [],
  });
  const { error, loading, visible, marketId, stationId, calendarDate, stationOptions, dataSource } =
    state;

  useEffect(() => {
    init();
  }, []);

  const init = () => {
    const { marketId, calendarDate } = formValue;
    const options = power.find((t) => t.marketId === marketId);
    onChangeRegion(marketId, options);

    const dataRange = [moment(calendarDate[0]), moment(calendarDate[1])];
    state.calendarDate = dataRange;
    setState({ calendarDate: dataRange });
    fetchData();
  };

  const fetchData = async () => {
    setState({ loading: true });
    const date = state.calendarDate;

    const param = {
      calendarDate: [date[0].format('YYYY-MM-DD'), date[1].format('YYYY-MM-DD')],
      stationId: state.stationId,
      type: '方案',
    };
    const res = await queryProvincialSpotBiddingPlan(param || {});
    if (res && res.statusCode === HttpCode.SUCCESS) {
      let { planList } = res?.data;

      planList = planList.map((t, i) => ({ ...t, index: i }));
      setState({ dataSource: planList });
    } else {
      message.error(res?.message || '系统异常');
    }
    setState({ loading: false });
  };

  const _onCancel = () => {
    setState({ visible: false });
    onPress({ index: 0 });
  };

  const _onSubmit = async () => {
    setState({ visible: false });
    onPress({ index: 1, data: dataSource });
  };

  const onChangeRegion = async (v, { children }) => {
    state.marketId = v;
    state.stationOptions = children;
    state.stationId = children?.[0]?.value;
    setState({
      marketId: v,
      stationOptions: children,
      stationId: children?.[0]?.value,
    });
  };

  const pipeline = useTablePipeline({ components: {} })
    .input({
      dataSource,
      columns: columns.filter((t) => t.code !== 'operation'),
    })
    .primaryKey('index');

  /**图表配置*/
  const getChartOption = (dataSource) => {
    const CODE1 = 'startOutput';
    const series = [
      {
        name: '电能量报价曲线',
        type: 'line',
        props: {
          step: 'end',
          symbol: 'circle',
        },
        color: '#2174FF',
        dataIndex: 'electricityPrice',
      },
    ];

    return {
      grid: { left: 20, top: 25, right: 20, bottom: 25, containLabel: true },
      series,
      dataset: {
        source: dataSource,
        dimensions: [CODE1, 'electricityPrice'],
      },
      tooltip: {},
      legend: {},
      xAxis: [{ type: 'category', boundaryGap: false }],
      yAxis: [
        {
          type: 'value',
          name: '单位:元/Mwh',
          nameTextStyle: {
            align: 'left',
          },
        },
      ],
    };
  };

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={loading}>
      取消
    </Button>,
    <Button
      key="dtest2"
      type="primary"
      onClick={_onSubmit}
      loading={loading}
      style={{ marginLeft: 16 }}
      disabled={!dataSource.length}
    >
      确定
    </Button>,
  ];

  const renderHeader = () => {
    return (
      <div className={styles.header}>
        <div className={styles.select}>
          <ConfigProvider locale={zh_CN}>
            <Space size={'middle'}>
              <Select
                value={marketId}
                style={{ width: 200 }}
                options={power}
                onChange={onChangeRegion}
              />
              <Select
                value={stationId}
                style={{ width: 240 }}
                options={stationOptions}
                showSearch
                filterOption={(input, { label }) => {
                  return label?.indexOf(input) >= 0;
                }}
                onChange={(e) => setState({ stationId: e })}
              />
              <RangePicker
                value={calendarDate}
                style={{ width: 260 }}
                format="YYYYMMDD"
                placeholder="请选择"
                separator={'-'}
                className={styles.datePicker}
                onChange={(e) => setState({ calendarDate: e })}
              />
              <Button type="primary" onClick={fetchData} className={styles.searchBtn}>
                查询
              </Button>
            </Space>
          </ConfigProvider>
        </div>
      </div>
    );
  };

  const renderContent = () => {
    if (loading) return <PageLoading />;
    if (!dataSource.length) return <TRDefault type="empty" />;
    if (error) return <TRDefault type="error" message={error} />;

    return (
      <div className={styles.bottom}>
        <div className={styles.chart}>
          <div className={styles.chartTitle}>价格曲线</div>
          <TjChart option={getChartOption(dataSource)} />
        </div>
        <TjTable
          style={{ flex: 1, overflowY: 'scroll', marginTop: 15 }}
          useVirtual="auto"
          defaultColumnWidth={90}
          {...pipeline.getProps()}
        />
      </div>
    );
  };

  return (
    <Modal
      className={styles.modal}
      centered
      width={1200}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <div className={styles.left}>
            <img src={planIcon} className={styles.titleLogo} />
            <span className={styles.title}>策略引用</span>
          </div>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        {renderHeader()}
        {renderContent()}
      </div>
    </Modal>
  );
};

class OutputPlanReferenceStrategy {
  __key__ = '';

  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ConfirmModalComponent
            {...props}
            onPress={(result) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new OutputPlanReferenceStrategy();
